﻿#region Copyright(c) 2006 ZO, All right reserved.
// -----------------------------------------------------------------------------
// Copyright(c) 2006 ZO, All right reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   1.  Redistribution of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//   2.  Redistribution in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//   3.  The name of the author may not be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// -----------------------------------------------------------------------------
#endregion


#region Using directives

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using ZO.SmartCore.Collections.Generic;
using ZO.SmartCore.Core;

#endregion

namespace ZO.SmartCore.Xml
{
    /// <summary>
    /// Provides Namespaces Support
    /// </summary>
    [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
    public class NamespaceList : DisposableObject, IEnumerable<KeyValuePair<string, string>>
    {

        #region Constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="NamespaceList"/> class.
        /// </summary>
        /// <param name="node">The node.</param>
        internal NamespaceList(Node node)
        {
            this.node = node;
        }
        #endregion

        #region Destructor

        #endregion

        #region Fields
        private Node node;
        private string _DefaultNamespace;
        internal OrderedDictionary<string, string> _InternalNamespaces = new OrderedDictionary<string, string>();

        #endregion

        #region Events

        #endregion

        #region Operators

        #endregion

        #region Properties
        /// <summary>Gets the default namespace URI of this node.</summary>
        /// <returns>The default namespace URI of this node. If there is no namespace URI, this property returns String.Empty.</returns>
        public string DefaultNamespace
        {
            get { return _DefaultNamespace; }
            set
            {
                if ((value != null) && (Uri.IsWellFormedUriString(value, UriKind.RelativeOrAbsolute)))
                {
                    Node currentNode = this.node;

                    string defaultUri;

                    while (currentNode != null)
                    {
                        defaultUri = currentNode.Namespaces.DefaultNamespace;

                        if (String.Compare(defaultUri, value) == 0)
                        {
                            return;
                        }
                        currentNode = currentNode.Parent;
                    }

                    _DefaultNamespace = value;

                }
            }
        }

        /// <summary>
        /// Gets an Dictionary containing the list of namespaces for this node. 
        /// </summary>
        /// <remarks>Do Not</remarks>
        private OrderedDictionary<string, string> InternalNamespaces
        {
            get
            {
                return this._InternalNamespaces;
            } // get
        }

        /// <summary>
        /// Gets or sets the value with the specified key.
        /// </summary>
        /// <value></value>
        public string this[string prefix]
        {
            get
            {
                return this.InternalNamespaces[prefix];
            }
            set
            {

                this.InternalNamespaces[prefix] = value;
            }
        }


        /// <summary>
        /// Gets the number of elements contained in the collection.
        /// </summary>
        /// <value></value>
        /// <returns>The number of elements contained in the collection.</returns>
        public int Count
        {
            get { return this.InternalNamespaces.Count; }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Override This Method To Dispose Unmanaged Resources.
        /// </summary>
        protected override void DisposeManagedResources()
        {
            base.DisposeManagedResources();
            this.InternalNamespaces.Clear();
        }

        /// <summary>
        /// Adds the namespace.
        /// </summary>
        /// <param name="prefix">The prefix.</param>
        /// <param name="uri">The URI.</param>
        public void Add(string prefix, string uri)
        {
            if (String.IsNullOrEmpty(prefix))
            {
                return;
            }

            if ((String.IsNullOrEmpty(uri) && (!Uri.IsWellFormedUriString(uri, UriKind.RelativeOrAbsolute))))
            {
                return;
            }


            Node currentNode = this.node;

            string uri2 = null;
            while (currentNode != null)
            {
                if (currentNode.Namespaces.Contains(prefix))
                {
                    uri2 = currentNode.Namespaces[prefix];
                }
                currentNode = currentNode.Parent;
            }

            if (String.IsNullOrEmpty(uri2))
            {
                this.InternalNamespaces.Add(prefix, uri);
            }
            else
            {
                if (String.Compare(uri, uri2, true, CultureInfo.CurrentCulture) != 0)
                {
                    this.InternalNamespaces.Add(prefix, uri);
                }
            }


        }

        /// <summary>
        /// Adds the namespace.
        /// </summary>
        /// <param name="prefix">The prefix.</param>
        /// <param name="uri">The URI.</param>
        public void Add(string prefix, Uri uri)
        {
            if (String.IsNullOrEmpty(prefix))
            {
                return;
            }
            if (uri == null)
            {
                return;
            }


            Node currentNode = this.node;

            string uri2 = null;
            while (currentNode != null)
            {
                if (currentNode.Namespaces.Contains(prefix))
                {
                    uri2 = currentNode.Namespaces[prefix];
                }
                currentNode = currentNode.Parent;
            }

            if (String.IsNullOrEmpty(uri2))
            {
                this.InternalNamespaces.Add(prefix, uri.ToString());
            }
            else
            {
                if (String.Compare(uri.ToString(), uri2, true, CultureInfo.CurrentCulture) != 0)
                {
                    this.InternalNamespaces.Add(prefix, uri.ToString());
                }
            }


        }

        /// <summary>
        /// Removes the namespace.
        /// </summary>
        /// <param name="prefix">The prefix.</param>
        public void Remove(string prefix)
        {
            if (String.IsNullOrEmpty(prefix))
            {
                return;
            }

            if (this.InternalNamespaces.Contains(prefix))
            {
                this.InternalNamespaces.Remove(prefix);
            }
        }

        /// <summary>
        /// Lookups the namespace.
        /// </summary>
        /// <param name="prefix">The prefix.</param>
        /// <returns></returns>
        public string LookupNamespace(string prefix)
        {
            if (prefix == null)
            {
                return String.Empty;
            }


            Node currentNode = this.node;

            while (currentNode != null)
            {
                if (currentNode.Namespaces.Contains(prefix))
                {
                    return currentNode.Namespaces[prefix];
                }
                currentNode = currentNode.Parent;
            }

            return String.Empty;
        }


        /// <summary>
        /// Determines whether [contains] [the specified prefix].
        /// </summary>
        /// <param name="prefix">The prefix.</param>
        /// <returns>
        /// 	<c>true</c> if [contains] [the specified prefix]; otherwise, <c>false</c>.
        /// </returns>
        /// <remarks>this method doesn't serach on parent node</remarks>
        public bool Contains(string prefix)
        {
            return this.Contains(prefix, false);
        }

        /// <summary>
        /// Determines whether [contains] [the specified prefix].
        /// </summary>
        /// <param name="prefix">The prefix.</param>
        /// <param name="searchParent">if set to <see langword="true"/> [search parent].</param>
        /// <returns>
        /// 	<c>true</c> if [contains] [the specified prefix]; otherwise, <c>false</c>.
        /// </returns>
        /// <remarks>this method doesn't serach on parent node</remarks>
        public bool Contains(string prefix, bool searchParent)
        {
            if (String.IsNullOrEmpty(prefix))
            {
                return false;
            }

            if (!(searchParent))
            {
                if (this.InternalNamespaces.Contains(prefix))
                {
                    return true;
                }

            }
            else
            {
                Node currentNode = this.node;

                while (currentNode != null)
                {
                    if (currentNode.Namespaces.Contains(prefix))
                    {
                        return true;
                    }
                    currentNode = currentNode.Parent;
                }
            }

            return false;
        }

        /// <summary>
        /// Removes all items
        /// </summary>
        /// <exception cref="System.NotSupportedException">The collection is read-only. </exception>
        public void Clear()
        {
            this.InternalNamespaces.Clear();
        }

        #region IEnumerable Members

        /// <summary>
        /// Returns an enumerator that iterates through a collection.
        /// </summary>
        /// <returns>
        /// An <see cref="T:System.Collections.IEnumerator"></see> object that can be used to iterate through the collection.
        /// </returns>
        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.InternalNamespaces.GetEnumerator();
        }

        /// <summary>
        /// Gets an collection containing all the values of the prefix in the <see cref="System.Collections.Generic.IDictionary{TKey, TValue}"></see>.
        /// </summary>
        /// <value></value>
        /// <returns>An collection containing the values of the object that implements <see cref="System.Collections.Generic.IDictionary{TKey, TValue}"></see>.</returns>
        public virtual ICollection<string> Prefixes
        {
            get
            {
                return this.InternalNamespaces.Keys;
            }
        }

        /// <summary>
        /// Gets an collection containing all the namespaces uri in the <see cref="System.Collections.Generic.IDictionary{TKey, TValue}"></see>.
        /// </summary>
        /// <value></value>
        /// <returns>An collection containing the values in the object that implements <see cref="System.Collections.Generic.IDictionary{TKey, TValue}"></see>.</returns>
        public virtual ICollection<string> NamespacesUri
        {
            get
            {

                return this.InternalNamespaces.Values;
            } // get
        }

        /// <summary>
        /// Returns an enumerator that iterates through the collection.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.Collections.Generic.IEnumerator`1"></see> that can be used to iterate through the collection.
        /// </returns>
        public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
        {
            return this.InternalNamespaces.GetEnumerator();
        }
        #endregion

        #endregion
    }
}
